package middleware

import (
	"github.com/gin-gonic/gin"
	"monitoring-api/pkg/jwt"
)

// AuthRequired 需要登录
func AuthRequired() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("authorization")
		claims, err := jwt.ParseToken(token)
		if err != nil {
			c.JSON(200, gin.H{
				"message": "身份已过期或者token错误",
				"error":   err.Error(),
			})
			c.Abort()
			return
		} else {
			//将user_id添加到上下文中
			c.Set("user_id", claims.UserID)
			c.Next()
		}

	}
}
